package com.center.growcenterserver.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.center.growcenterserver.mapper.StudentCourseMapper;
import com.center.growcenterserver.model.domain.StudentCourse;
import com.center.growcenterserver.service.GradeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;


@Slf4j
@Service
public class GradeServiceImpl extends ServiceImpl<StudentCourseMapper, StudentCourse> implements GradeService {
    public static final String UPLOAD_DIR = "/src/file";

    private StudentCourseMapper studentCourseMapper;

    @Autowired
    public void GradeUploadServiceImpl(StudentCourseMapper studentCourseMapper) {
        this.studentCourseMapper = studentCourseMapper;
    }

    static {
        Path dir = Paths.get(UPLOAD_DIR);
        if (!Files.exists(dir)) {
            try {
                Files.createDirectories(dir);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    public ResponseEntity<String> uploadFile(MultipartFile file, String courseId) {
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body("请提供文件");
        }

        try {
            Path filePath = Paths.get(UPLOAD_DIR + courseId + "-" + file.getOriginalFilename());
            Files.copy(file.getInputStream(), filePath);

            // 假设有一个方法可以解析文件并存储到数据库中
            studentCourseMapper.parseAndStoreGrades(filePath.toString());

            return ResponseEntity.ok("文件上传成功：" + file.getOriginalFilename());
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body("文件上传失败：" + e.getMessage());
        }
    }
}
